import React, { useEffect, useState, Key } from "react";
import { useNavigate } from "react-router-dom";
// 引入antd的样式
import { Button, Form, Input, Card, Table, message, Tooltip } from "antd";
import {
  SearchOutlined,
  EditOutlined,
  DeleteOutlined,
} from "@ant-design/icons";
//引入api中请求的方法
import {
  getHosSetListRequest,
  DeleteDataAccordingToIdRequest,
  BatchDeleteDataRequest,
} from "@/api/hospital/hospitalSet";
// 引入接受的值的判别
import type {
  getHosSetListRecordsType,
  getHosSetListItemsType,
} from "@api/hospital/model/hospitalSetTypes";
// 引入样式
import style from "./index.module.css";
import { searchHosFinishPraType } from "./type";
export default function HospitalSet() {
  const navigate = useNavigate();
  // 将请求来的值保持在自己的状态里 后续使用
  // 表单数据
  const [hospitalList, setHospitalList] = useState<getHosSetListRecordsType>(
    []
  );
  const [current, setCurrent] = useState(1);
  // 定义pageSize(每页的数量)
  const [pageSize, setPageSize] = useState(15);
  // 定义total(总个数)
  const [total, setTotal] = useState(0);
  //定义isLoading(table是否加载中)
  const [isLoading, setIsLoading] = useState(false);
  // 定义搜索内的状态
  const [fieldValue, setFieldValue] = useState<searchHosFinishPraType>({});
  const [isDelete, setDelete] = useState(true);
  // 定义批量删除按钮的样式
  const [btnStyle, setBtnStyle] = useState(true);
  // 定义保存批量选择的id
  const [idList, setIdList] = useState<Key[]>([]);
  // 初始化时获取数据
  useEffect(() => {
    setIsLoading(true);
    getHosSetList();
  }, [current, pageSize, fieldValue, isDelete]);
  // 回调函数
  // 请求分页列表的数据
  const getHosSetList = async () => {
    // 发送请求获取返回值
    const res = await getHosSetListRequest({
      page: current,
      limit: pageSize,
      ...fieldValue,
    });
    setHospitalList(res.records);
    // 修改总页数
    setTotal(res.total);
    // 修改加载中的状态
    setIsLoading(false);
  };
  // 模糊查询
  const searchHosFinishHandle = (fieldValue: searchHosFinishPraType) => {
    setFieldValue(fieldValue);
  };

  // 点击切换页码
  const isChange = (current: number, pageSize: number) => {
    setCurrent(current);
    setPageSize(pageSize);
  };
  // 删除的函数
  const DeleteData = (id: string) => {
    return async () => {
      await DeleteDataAccordingToIdRequest(id);
      message.success("删除医院成功");
      setDelete(!isDelete);
    };
  };
  // 批量删除的函数
  const DeleteBatchData = async () => {
    await BatchDeleteDataRequest(idList);
    // 弹出
    message.success("删除成功");
    // 清空idList里的数据
    setIdList([]);
    // 控制状态让他重新渲染
    getHosSetList();
    // 改变批量删除按钮的状态
    setBtnStyle(true);
  };
  const columns = [
    {
      title: "序号",
      width: 60,
      dataIndex: "index",
      render(_: any, __: any, index: number) {
        return index + 1;
      },
    },
    {
      title: "医院名称",
      dataIndex: "hosname",
    },
    {
      title: "医院编号",
      dataIndex: "hoscode",
    },
    {
      title: "api基础路径",
      dataIndex: "apiUrl",
    },
    {
      title: "签名",
      dataIndex: "signKey",
    },
    {
      title: "联系人姓名",
      dataIndex: "contactsName",
    },
    {
      title: "联系人手机",
      dataIndex: "contactsPhone",
    },
    {
      title: "操作",
      width: 120,
      fixed: "right" as "right",
      dataIndex: "do",
      render(_: any, data: getHosSetListItemsType) {
        const { id } = data;
        return (
          <div>
            {/* 修改 */}
            <Tooltip title="修改医院" color={"green"}>
              <Button
                type="primary"
                icon={<EditOutlined />}
                className={style.mr}
                onClick={() => {
                  navigate(`/syt/hospital/changeResult/${id}`);
                }}
              ></Button>
            </Tooltip>

            {/* 删除 */}
            <Tooltip title="删除医院" color={"pink"}>
              <Button
                type="primary"
                danger
                icon={<DeleteOutlined />}
                onClick={DeleteData(id)}
              ></Button>
            </Tooltip>
          </div>
        );
      },
    },
  ];
  return (
    <div>
      <Card>
        <Form
          name="basic"
          wrapperCol={{ span: 30 }}
          layout="inline"
          onFinish={searchHosFinishHandle}
        >
          <Form.Item name="hosname">
            <Input placeholder="医院名称" />
          </Form.Item>

          <Form.Item name="hosname">
            <Input placeholder="医院编号" />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 0, span: 16 }}>
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
              查询
            </Button>
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 0, span: 16 }}>
            <Button type="default" htmlType="reset">
              清空
            </Button>
          </Form.Item>
        </Form>
        <div className={style.mt}>
          <Button
            type="primary"
            className={style.mr}
            onClick={() => navigate("/syt/hospital/addResult")}
          >
            添加
          </Button>
          <Button
            type="primary"
            danger
            disabled={btnStyle}
            onClick={DeleteBatchData}
          >
            批量删除
          </Button>
        </div>
        {/* 列表的设置 */}
        <Table
          className={style.mt}
          columns={columns}
          // 这里的值是我获取到的值
          dataSource={hospitalList}
          scroll={{ x: 1100 }}
          bordered
          loading={isLoading}
          //在table中 要求dataSource中有key属性,但是如果真的没有key 则可以使用rowKey属性指定dataSource中的一个属性作为Key
          rowKey="id"
          // 弹出可选框
          rowSelection={{
            onChange(idList: Key[]) {
              // 如果有被选中的
              if (idList) {
                // 更改批量删除按钮的样式
                setBtnStyle(!idList.length);
                //保存被选中的id
                setIdList(idList);
              }
            },
          }}
          pagination={{
            //页码的配置：当前页码
            current,
            //总数据的数量
            total,
            //每页条数
            pageSize,
            //展示更改每页条数的选项(默认total大于50条的时候开启)
            pageSizeOptions: [2, 3, 4, 5],
            //是否直接开启更新每页条数的选项
            showSizeChanger: true,
            showTotal(total) {
              return `总共有${total}条数据`;
            },
            onChange: isChange,
          }}
        />
      </Card>
    </div>
  );
}
